<template>
  <div class="logs-container">
    <div class="header">
      <div class="header-left">
        <h2>操作日志</h2>
        <el-tag type="info" class="log-count">共 {{ (logs || []).length }} 条记录</el-tag>
      </div>
      <div class="header-right">
        <el-button @click="refreshLogs" icon="el-icon-refresh">刷新</el-button>
        <el-button type="primary" @click="exportLogs" icon="el-icon-download">导出</el-button>
      </div>
    </div>
    
    <el-card class="filter-card" shadow="never">
      <div class="filter-content">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="用户名">
            <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable></el-input>
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select v-model="filterForm.operationType" placeholder="请选择操作类型" clearable>
              <el-option label="登录" value="LOGIN"></el-option>
              <el-option label="登出" value="LOGOUT"></el-option>
              <el-option label="创建" value="CREATE"></el-option>
              <el-option label="更新" value="UPDATE"></el-option>
              <el-option label="删除" value="DELETE"></el-option>
              <el-option label="迁移" value="MIGRATE"></el-option>
              <el-option label="备份" value="BACKUP"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="操作模块">
            <el-select v-model="filterForm.operationModule" placeholder="请选择操作模块" clearable>
              <el-option label="认证" value="AUTHENTICATION"></el-option>
              <el-option label="服务器" value="SERVER"></el-option>
              <el-option label="迁移" value="MIGRATION"></el-option>
              <el-option label="用户" value="USER"></el-option>
              <el-option label="系统" value="SYSTEM"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="结果">
            <el-select v-model="filterForm.result" placeholder="请选择结果" clearable>
              <el-option label="成功" value="SUCCESS"></el-option>
              <el-option label="失败" value="FAILURE"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="filterForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable>
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="filterForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable>
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="applyFilter" icon="el-icon-search">搜索</el-button>
            <el-button @click="resetFilter" icon="el-icon-refresh-left">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <el-table 
      :data="filteredLogs" 
      style="width: 100%" 
      border
      class="logs-table"
      v-loading="loading"
    >
      <el-table-column prop="username" label="用户名" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="operationType" label="操作类型" width="120">
        <template slot-scope="scope">
          <el-tag :type="getOperationTypeTagType(scope.row.operationType)">
            {{ getOperationTypeText(scope.row.operationType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operationModule" label="操作模块" width="120">
        <template slot-scope="scope">
          {{ getOperationModuleText(scope.row.operationModule) }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
      <el-table-column prop="result" label="结果" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.result === 'SUCCESS' ? 'success' : 'danger'">
            {{ scope.row.result === 'SUCCESS' ? '成功' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="ipAddress" label="IP地址" width="150"></el-table-column>
      <el-table-column prop="createdAt" label="操作时间" width="180">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            @click="showDetails(scope.row)"
            icon="el-icon-view"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalFilteredLogs"
      >
      </el-pagination>
    </div>
    
    <!-- 日志详情对话框 -->
    <el-dialog
      title="操作日志详情"
      :visible.sync="detailDialogVisible"
      width="600px"
      class="detail-dialog"
    >
      <el-form label-width="120px" class="detail-form">
        <el-form-item label="用户名：">
          <span>{{ currentLog.username }}</span>
        </el-form-item>
        
        <el-form-item label="操作类型：">
          <el-tag :type="getOperationTypeTagType(currentLog.operationType)">
            {{ getOperationTypeText(currentLog.operationType) }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="操作模块：">
          <el-tag>{{ getOperationModuleText(currentLog.operationModule) }}</el-tag>
        </el-form-item>
        
        <el-form-item label="结果：">
          <el-tag :type="currentLog.result === 'SUCCESS' ? 'success' : 'danger'">
            {{ currentLog.result === 'SUCCESS' ? '成功' : '失败' }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="描述：">
          <span>{{ currentLog.description }}</span>
        </el-form-item>
        
        <el-form-item label="IP地址：" v-if="currentLog.ipAddress">
          <span>{{ currentLog.ipAddress }}</span>
        </el-form-item>
        
        <el-form-item label="用户代理：" v-if="currentLog.userAgent">
          <span>{{ currentLog.userAgent }}</span>
        </el-form-item>
        
        <el-form-item label="操作时间：">
          <span>{{ formatDateTime(currentLog.createdAt) }}</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import moment from 'moment'

export default {
  name: 'Logs',
  data() {
    return {
      detailDialogVisible: false,
      loading: false,
      currentLog: {},
      filterForm: {
        username: '',
        operationType: '',
        operationModule: '',
        result: '',
        startTime: '',
        endTime: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 10
      }
    }
  },
  computed: {
    // 重新定义计算属性，避免与data中的属性冲突
    logList() {
      return this.$store.state.logs.logs || []
    },
    filteredLogs() {
      // 确保logs存在，如果不存在则使用空数组
      let result = this.logList || [];
      
      // 应用过滤条件
      if (this.filterForm.username) {
        result = result.filter(log => 
          log.username && log.username.toLowerCase().includes(this.filterForm.username.toLowerCase())
        );
      }
      
      if (this.filterForm.operationType) {
        result = result.filter(log => log.operationType === this.filterForm.operationType);
      }
      
      if (this.filterForm.operationModule) {
        result = result.filter(log => log.operationModule === this.filterForm.operationModule);
      }
      
      if (this.filterForm.result) {
        result = result.filter(log => log.result === this.filterForm.result);
      }
      
      // 时间范围过滤
      if (this.filterForm.startTime || this.filterForm.endTime) {
        result = result.filter(log => {
          if (!log.createdAt) return false;
          const logTime = new Date(log.createdAt).getTime();
          const startTime = this.filterForm.startTime ? new Date(this.filterForm.startTime).getTime() : 0;
          const endTime = this.filterForm.endTime ? new Date(this.filterForm.endTime).getTime() : Date.now();
          return logTime >= startTime && logTime <= endTime;
        });
      }
      
      // 按时间倒序排列
      result.sort((a, b) => {
        if (!a.createdAt || !b.createdAt) return 0;
        return new Date(b.createdAt) - new Date(a.createdAt);
      });
      
      // 应用分页
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return result.slice(start, end);
    },
    // 添加一个计算属性来获取过滤后的总日志数（用于分页）
    totalFilteredLogs() {
      // 确保logs存在，如果不存在则使用空数组
      let result = this.logList || [];
      
      // 应用过滤条件
      if (this.filterForm.username) {
        result = result.filter(log => 
          log.username && log.username.toLowerCase().includes(this.filterForm.username.toLowerCase())
        );
      }
      
      if (this.filterForm.operationType) {
        result = result.filter(log => log.operationType === this.filterForm.operationType);
      }
      
      if (this.filterForm.operationModule) {
        result = result.filter(log => log.operationModule === this.filterForm.operationModule);
      }
      
      if (this.filterForm.result) {
        result = result.filter(log => log.result === this.filterForm.result);
      }
      
      // 时间范围过滤
      if (this.filterForm.startTime || this.filterForm.endTime) {
        result = result.filter(log => {
          if (!log.createdAt) return false;
          const logTime = new Date(log.createdAt).getTime();
          const startTime = this.filterForm.startTime ? new Date(this.filterForm.startTime).getTime() : 0;
          const endTime = this.filterForm.endTime ? new Date(this.filterForm.endTime).getTime() : Date.now();
          return logTime >= startTime && logTime <= endTime;
        });
      }
      
      return result.length;
    }
  },
  async created() {
    await this.refreshLogs();
  },
  methods: {
    ...mapActions('logs', ['fetchLogs']),
    async refreshLogs() {
      this.loading = true
      try {
        await this.fetchLogs()
        this.$message.success('日志刷新成功')
      } catch (error) {
        this.$message.error('日志刷新失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    async exportLogs() {
      try {
        // 获取过滤后的日志数据
        const logsToExport = this.filteredLogs
        
        // 创建CSV内容
        let csvContent = '\uFEFF用户名,操作类型,操作模块,描述,结果,IP地址,操作时间\n'
        logsToExport.forEach(log => {
          csvContent += `"${log.username || ''}","${this.getOperationTypeText(log.operationType)}","${this.getOperationModuleText(log.operationModule)}","${log.description || ''}","${log.result === 'SUCCESS' ? '成功' : '失败'}","${log.ipAddress || ''}","${this.formatDateTime(log.createdAt)}"\n`
        })
        
        // 创建下载链接
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.setAttribute('href', url)
        link.setAttribute('download', `操作日志_${new Date().toISOString().slice(0, 10)}.csv`)
        link.style.visibility = 'hidden'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        this.$message.success('日志导出成功')
      } catch (error) {
        this.$message.error('日志导出失败: ' + error.message)
      }
    },
    
    getOperationTypeText(type) {
      const typeMap = {
        'LOGIN': '登录',
        'LOGOUT': '登出',
        'CREATE': '创建',
        'UPDATE': '更新',
        'DELETE': '删除',
        'MIGRATE': '迁移',
        'BACKUP': '备份'
      }
      return typeMap[type] || type
    },
    
    getOperationModuleText(module) {
      const moduleMap = {
        'AUTHENTICATION': '认证',
        'SERVER': '服务器',
        'MIGRATION': '迁移',
        'USER': '用户',
        'SYSTEM': '系统'
      }
      return moduleMap[module] || module
    },
    
    getOperationTypeTagType(type) {
      const typeColorMap = {
        'LOGIN': 'primary',
        'LOGOUT': 'info',
        'CREATE': 'success',
        'UPDATE': 'warning',
        'DELETE': 'danger',
        'MIGRATE': '',
        'BACKUP': 'info'
      }
      return typeColorMap[type] || 'info'
    },
    
    formatDateTime(datetime) {
      return datetime ? moment(datetime).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    
    showDetails(log) {
      this.currentLog = log
      this.detailDialogVisible = true
    },
    
    applyFilter() {
      // 过滤逻辑已经在computed属性中实现
      this.pagination.currentPage = 1
    },
    
    resetFilter() {
      this.filterForm = {
        username: '',
        operationType: '',
        operationModule: '',
        result: '',
        startTime: '',
        endTime: ''
      }
      this.pagination.currentPage = 1
    },
    
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.pagination.currentPage = 1
    },
    
    handleCurrentChange(page) {
      this.pagination.currentPage = page
    }
  }
}
</script>

<style scoped>
.logs-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.log-count {
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.filter-content {
  padding: 20px 0;
}

.filter-form ::v-deep .el-form-item {
  margin-bottom: 0;
}

.logs-table {
  margin-bottom: 20px;
}

.logs-table ::v-deep .el-table__row:hover {
  background-color: #f5f7fa;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.detail-dialog ::v-deep .el-dialog__body {
  padding: 20px;
}

.detail-form ::v-deep .el-form-item {
  margin-bottom: 15px;
}

.detail-form ::v-deep .el-form-item__label {
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-left {
    justify-content: center;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .filter-content {
    padding: 15px 0;
  }
  
  .filter-form ::v-deep .el-form-item {
    margin-bottom: 15px;
    width: 100%;
  }
  
  .filter-form ::v-deep .el-form-item__content {
    width: 100%;
  }
  
  .filter-form ::v-deep .el-input,
  .filter-form ::v-deep .el-select {
    width: 100% !important;
  }
}
</style>